﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VoicePhone.Common
{
    public class RegistryHelper
    {
        public static RegistryKey RootKey = Registry.CurrentUser;

        /// <summary>
        /// 添加或修改注册表项
        /// </summary>
        /// <param name="path"></param>
        /// <param name="keyName"></param>
        /// <param name="value"></param>
        public static void AddRegistryNode(String path, String keyName, object value)
        {
            if (null == RootKey.OpenSubKey(path))
            {
                RootKey.CreateSubKey(path);
            }

            RegistryKey key = RootKey.OpenSubKey(path, true);
            key.SetValue(keyName, value);
        }

        /// <summary>
        /// 删除注册表项
        /// </summary>
        /// <param name="path"></param>
        /// <param name="keyName"></param>
        public static void DeleteRegistryNode(String path, String keyName)
        {
            if (HasRegistryNode(path, keyName))
            {
                RegistryKey key = RootKey.OpenSubKey(path, true);
                key.DeleteValue(keyName);
            }
        }

        /// <summary>
        /// 包含注册表项
        /// </summary>
        /// <param name="path"></param>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public static bool HasRegistryNode(String path, string keyName)
        {
            if (null == RootKey.OpenSubKey(path))
            {
                RootKey.CreateSubKey(path);
            }
            RegistryKey key = RootKey.OpenSubKey(path);
            return key.GetValueNames().Any(name => name.Equals(keyName));
        }


        /// <summary>
        /// 读取注册表项
        /// </summary>
        /// <param name="path"></param>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public static string ReadRegistryNode(String path, string keyName)
        {
            if (null == RootKey.OpenSubKey(path))
            {
                RootKey.CreateSubKey(path);
            }
            RegistryKey key = RootKey.OpenSubKey(path);
            var val = key.GetValue(keyName);
            if (null != val)
	        {
                return val.ToString();
	        }
            return string.Empty;
        }
    }
}
